package com.ruoyi.project.ins.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.http.OkHttpUtils;
import com.ruoyi.project.ins.domain.InsWebProxy;
import com.ruoyi.project.ins.domain.InstagramAccount;
import com.ruoyi.project.ins.utils.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

@Slf4j
public class InsApi {

    private static final String APP_ID = "567067343352427";

    public static String getUserIdByUsername(String username, InstagramAccount account, InsWebProxy proxy) {
        String url = "https://i.instagram.com/api/v1/users/web_profile_info/?username=" + username;
        log.info("即将构建请求头: {}，代理参数：{}", account, proxy);
        Map<String, String> headers = buildBaseHeaders(account);
        HttpResult resp = OkHttpUtils.sendGetWithProxy(url, headers, proxy);
        if (resp.getStatusCode() == 200) {
            try {
                JSONObject json = JSON.parseObject(resp.getBody());
                return json.getJSONObject("data").getJSONObject("user").getString("id");
            } catch (Exception e) {
                log.error("解析 user_id 异常", e);
            }
        } else {
            log.error("获取 user_id 失败：{}，内容={}", resp.getStatusCode(), resp.getBody());
        }
        return null;
    }

    public static String getThreadIdByUserId(String targetUserId, InstagramAccount account, InsWebProxy proxy) {
        String url = "https://i.instagram.com/api/v1/direct_v2/inbox/?persistentBadging=true&use_unified_inbox=true";
        log.info("即将构建请求头: {}，代理参数：{}", account, proxy);
        Map<String, String> headers = buildBaseHeaders(account);

        HttpResult resp = OkHttpUtils.sendGetWithProxy(url, headers, proxy);
        if (resp.getStatusCode() != 200) {
            log.error("获取 inbox 失败：{}", resp.getBody());
            return null;
        }

        try {
            JSONObject inbox = JSON.parseObject(resp.getBody());
            for (Object threadObj : inbox.getJSONObject("inbox").getJSONArray("threads")) {
                JSONObject thread = (JSONObject) threadObj;
                for (Object userObj : thread.getJSONArray("users")) {
                    JSONObject user = (JSONObject) userObj;
                    if (targetUserId.equals(user.getString("pk"))) {
                        return thread.getString("thread_id");
                    }
                }
            }
        } catch (Exception e) {
            log.error("解析 thread_id 异常", e);
        }
        return null;
    }

    public static HttpResult smartSend(InstagramAccount account, String text, String username, String recipientUserId,
        String profileUserId, InsWebProxy proxy) {
        if (recipientUserId == null && username != null) {
            recipientUserId = getUserIdByUsername(username, account, proxy);
            if (recipientUserId == null) throw new RuntimeException("无法获取用户ID");
        }

        String threadId = getThreadIdByUserId(recipientUserId, account, proxy);
        return sendMessage(account, text, threadId, threadId == null ? recipientUserId : null, profileUserId, proxy);
    }

    public static HttpResult sendMessage(InstagramAccount account, String text, String threadId, String recipientUserId,
        String profileUserId, InsWebProxy proxy) {

        assert (threadId != null || recipientUserId != null);
        assert (text != null || profileUserId != null);

        String uuid = UUID.randomUUID().toString();
        log.info("即将构建发消息请求头: {}，代理参数：{}", account, proxy);
        Map<String, String> headers = buildPostHeaders(account);

        Map<String, String> payload = new LinkedHashMap<>();
        payload.put("action", "send_item");
        payload.put("_uuid", account.getUuidStr());
        payload.put("client_context", uuid);
        payload.put("mutation_token", uuid);

        if (threadId != null) {
            payload.put("thread_ids", "[" + threadId + "]");
        } else {
            payload.put("recipient_users", "[[\"" + recipientUserId + "\"]]");
        }

        String url;
        if (text != null && profileUserId == null) {
            url = "https://i.instagram.com/api/v1/direct_v2/threads/broadcast/text/";
            payload.put("text", text);
        } else if (profileUserId != null && text == null) {
            url = "https://i.instagram.com/api/v1/direct_v2/threads/broadcast/profile/";
            payload.put("profile_user_id", profileUserId);
        } else {
            // 名片+文本
            url = "https://i.instagram.com/api/v1/direct_v2/threads/broadcast/profile/";
            payload.put("profile_user_id", profileUserId);
            HttpResult profileResp = OkHttpUtils.sendPostWithProxy(url, headers, payload, proxy);
            if (profileResp.getStatusCode() != 200) {
                return profileResp;
            }
            payload.clear();
            payload.put("action", "send_item");
            payload.put("_uuid", account.getUuidStr());
            payload.put("client_context", uuid);
            payload.put("mutation_token", uuid);
            payload.put("text", text);
            if (threadId != null) payload.put("thread_ids", "[" + threadId + "]");
            else payload.put("recipient_users", "[[\"" + recipientUserId + "\"]]");
            url = "https://i.instagram.com/api/v1/direct_v2/threads/broadcast/text/";
        }

        return OkHttpUtils.sendPostWithProxy(url, headers, payload, proxy);
    }

    public static Boolean checkAccountAlive(InstagramAccount account, InsWebProxy proxy) {
        String url = "https://www.instagram.com/api/v1/users/web_profile_info/?username=" + account.getUsername();
        log.info("即将构建请求头: {}，代理参数：{}", account, proxy);
        Map<String, String> headers = buildBaseHeaders(account);

        HttpResult resp = OkHttpUtils.sendGetWithProxy(url, headers, proxy);
        if (resp.getStatusCode() == 200) {
            try {
                JSONObject json = JSON.parseObject(resp.getBody());
                return json.containsKey("data") && json.getJSONObject("data").containsKey("user");
            } catch (Exception e) {
                log.error("解析账号存活状态异常", e);
                return null;
            }
        } else if (resp.getStatusCode() == 404 || resp.getBody().contains("challenge_required")) {
            return false;
        }
        return null;
    }

    public static Map<String, Object> getCurrentUser(InstagramAccount account, InsWebProxy proxy) {
        String url = "https://i.instagram.com/api/v1/accounts/current_user/";
        log.info("即将构建请求头: {}，代理参数：{}", account, proxy);
        Map<String, String> headers = buildBaseHeaders(account);

        HttpResult resp = OkHttpUtils.sendGetWithProxy(url, headers, proxy);
        Map<String, Object> result = new HashMap<>();
        if (resp.getStatusCode() == 200) {
            try {
                JSONObject data = JSON.parseObject(resp.getBody());
                // ✅ 从 header 获取 claim，而不是 body
                String claim = null;
                if (resp.getHeaders() != null) {
                    claim = resp.getHeaders().get("X-IG-Set-WWW-Claim");
                }
                result.put("claim", StringUtils.isNotBlank(claim) ? claim : StringUtils.EMPTY);
                String username = data.getJSONObject("user").getString("username");
                // 账号正常
                result.put("status", "normal");
                result.put("username", username);
                return result;
            } catch (Exception e) {
                log.error("解析当前用户异常", e);
            }
        } else if (resp.getBody().contains("challenge_required")) {
            // 账号被封
            result.put("status", "abnormal");
            return result;
        }
        return null;
    }

    private static Map<String, String> buildBaseHeaders(InstagramAccount account) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + account.getBearerToken());
        headers.put("User-Agent", "Instagram 321.0.0.39.106 Android (...)");
        headers.put("IG-Intended-User-ID", account.getUserId());
        headers.put("IG-U-DS-User-ID", account.getUserId());
        headers.put("IG-U-RUR", account.getRur());
        headers.put("X-IG-App-ID", APP_ID);
        String wwwClaim = StringUtils.isNotBlank(account.getWwwClaim()) ? account.getWwwClaim() : "0";
        headers.put("X-IG-WWW-Claim", wwwClaim);
        headers.put("X-Mid", account.getMid());
        return headers;
    }

    private static Map<String, String> buildPostHeaders(InstagramAccount account) {
        Map<String, String> headers = buildBaseHeaders(account);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        headers.put("X-IG-Device-ID", account.getDeviceId());
        headers.put("X-IG-Timezone-Offset", "28800");
        return headers;
    }
}
